<?php

namespace Qwadmin\Controller;
class WithdrawController extends ComController{
    /**
     *  提现记录页
     */
    public function index(){
        $uid = session("user")['uid'];
        $date = I("date" , 0 , 'intval');
        $is_manager = session("user")['is_manager'];
		$start_date = htmlspecialchars(I("start_date" , '') , ENT_NOQUOTES);
		$end_date = htmlspecialchars(I("end_date" , '') , ENT_NOQUOTES);
		if(!empty($start_date)){
			//检查日期是否有效
			list($y,$m,$d)=explode('-',$start_date);
			if(checkdate($m,$d,$y)){
				$map["DATE_FORMAT(pay_time , '%Y-%m-%d')"] = array(array('EGT',$start_date));
			}else{
				$start_date = '';
			}
		}
		if(!empty($end_date)){
			//检查日期是否有效
			list($y,$m,$d)=explode('-',$end_date);
			if(checkdate($m,$d,$y)){
				$map["DATE_FORMAT(pay_time , '%Y-%m-%d')"][] = array('LT',$end_date);
			}else{
				$end_date = '';
			}
		}
		//默认查询当前的数据
		if(empty($start_date) && empty($end_date)){
			$start_date = date('Y-m-d',time());
			$end_date = date('Y-m-d',strtotime("+1 day"));
			$map["DATE_FORMAT(pay_time , '%Y-%m-%d')"] = array(array('EGT',strtotime($start_date)));
			$map["DATE_FORMAT(pay_time , '%Y-%m-%d')"][] = array('LT',strtotime($end_date));
		}
		
        $map['status'] = 1;
        if($date!= 0 ){
            //$map["DATE_FORMAT(pay_time , '%Y%m%d')"] = $date;
        }
        if($is_manager == 0){
            $map['uid'] = $uid;
        }
        $data = D("WithdrawLog")->getList($map);
        $this->assign("data" , $data);
		$this->assign("start_date" , $start_date);
		$this->assign("end_date" , $end_date);
        $this->display();
    }
    
    /**
     *  接收提现
     */
    public function hundle(){
        if(!IS_AJAX || !IS_POST){
            header("HTTP/1.0 404 Not Found");//404状态码  
            die;
        }
        $uid = session("user")['uid'];
        
        //检测是否能够提现
        $checkWithdraw = D("WithdrawLog")->canWithdraw($uid);
        if($checkWithdraw['status'] != 1){
            $this->ajaxReturn($checkWithdraw);          //如果不是一级代理商，或者今天已经提现
        }
        
        $amount = htmlspecialchars(I("amount"));
        if(!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $amount)){
            $this->ajaxReturn(['status' => 0 , 'msg' => '非法操作']);
        }
        
        if($amount <=0){
            $this->ajaxReturn(['status' => 0 , 'msg' => '提现金额必须大于0']);
        }
        
        $userInfo = D("user")->findUser(['uid' => $uid]);
        if($amount > $userInfo['money']){
            $this->ajaxReturn(['status' => 0 , 'msg' => '您的余额不足']);
        }
        
        if($userInfo['alipay'] == ''){
            $this->ajaxReturn(['status' => 0 , 'msg' => '您还未设置收款支付宝账号']);
        }
        
        if($userInfo['truename'] == ''){
            $this->ajaxReturn(['status' => 0 , 'msg' => '您还未设置收款支付宝姓名']);
        }
        
        //开始写入提现日志
        $out_biz_no = createOrderId();
        $data =  [
            'uid'       => $uid,
            'amount'    => $amount,
            'alipay'    => $userInfo['alipay'],
            'realname'  => $userInfo['truename'],
            'out_biz_no'    => $out_biz_no,
            'create_time'   => date('Y-m-d H:i:s'),
            'status'        => 0
        ];
        D("WithdrawLog")->add_log($data);
        //余额相应的减除掉
        D("user")->setDecAmount($uid , $amount);
        
        //开始向支付宝申请打款
        $pay_info = array(
		'order_sn'=>$out_biz_no,
		'account'=> $userInfo['alipay'],                //收款支付账号
		'account_realname'=> $userInfo['realname'],     //收款支付宝姓名
		'amount'=> $amount,
		'remark'=> C("PARAMS") . '提现',
	);
	$pay_code = "alipayx";
	$gateway = D("Payment","Api")->gateway($pay_code,$pay_info);
        
        if($gateway['status'] == 'success'){
            //提现成功，修改订单状态，写入回执行信
            D("WithdrawLog")->setOrderInfo($out_biz_no , [
                'order_id'  => $gateway['response']['order_id'],
                'pay_time'  => $gateway['response']['pay_date'],
                'status'    => 1,
            ]);
            $this->ajaxReturn(['status' => 1 , 'msg' => '现金已经转入您的支付，请查收']);
        }else{
           //余额还原
            D("user")->setIncAmount($uid , $amount);
            $this->ajaxReturn(['status' => 0 , 'msg' => $gateway['info'] ]);
        }
        
    }
    
    
    /**
     *  提现页
     */
    public function add(){
        $uid = session("user")['uid'];
        $userInfo = D("user")->findUser(['uid' => $uid]);
        $this->assign("data" , $userInfo);
        $this->display();
    }
	
	/**
	* 提现记录
	**/
	public function withdraw_requests(){
		$page = I("p", 1, 'intval');
		$start_date = htmlspecialchars(I("start_date" , '') , ENT_NOQUOTES);
		$end_date = htmlspecialchars(I("end_date" , '') , ENT_NOQUOTES);
		if(!empty($start_date)){
			//检查日期是否有效
			list($y,$m,$d)=explode('-',$start_date);
			if(checkdate($m,$d,$y)){
				$pram["start_date"] = strtotime($start_date);
			}else{
				$start_date = '';
			}
		}
		if(!empty($end_date)){
			//检查日期是否有效
			list($y,$m,$d)=explode('-',$end_date);
			if(checkdate($m,$d,$y)){
				$pram["end_date"] = strtotime($end_date);
			}else{
				$end_date = '';
			}
		}
		//默认查询当前的数据
		if(empty($start_date) && empty($end_date)){
			$start_date = date('Y-m-d',strtotime("-1 month"));
			$end_date = date('Y-m-d',strtotime("+1 day"));
			$pram["start_date"] = strtotime($start_date);
			$pram["end_date"] = strtotime($end_date);
		}
		$pram['uid']=session('uid');
		$pram['page']=$page;
		$data = D('WithdrawLog')->getList($pram);
		
		$pagebar = new \Think\Page($data['count'], 10);
		
		$this->assign("data", $data);
        $this->assign("page", $pagebar->show());
		$this->assign("start_date" , $start_date);
		$this->assign("end_date" , $end_date);
		$this->display();
	}
	
	/**
	* 提现详情
	**/
	public function withdraw_viwe(){
		$id = I("id", 0, 'intval');
		if(empty($id)){
			die('提现申请编号错误');
		}
		$WithdrawLog_info = D('WithdrawLog')->selOrderInfo($id);
		if(empty($WithdrawLog_info)){
			die('你没有权限查看此申请');
		}
		//获取订单用户的权限
		$member_level = D('Member')->getUserGid($WithdrawLog_info['uid']);
		//var_dump($member_level);
		$is_bool = false;
		if($this->USER['level']==1 && $member_level==3){//超管只能查看所有渠道的申请
			$is_bool = true;
		}elseif($this->USER['level']==3){//渠道只能看自己及其下级代理的申请
			$uid_ret = M('member')->field('uid')->where(['pid'=>session('uid')])->select();
			$uid_arr = [];
			foreach($uid_ret as $value){
				$uid_arr[] = $value['uid'];
			}
			$uid_arr[]=session('uid');
			if(in_array($WithdrawLog_info['uid'],$uid_arr)){
				$is_bool = true;
			}
		}elseif($this->USER['level']==4 && $WithdrawLog_info['uid']==session('uid')){//代理只能查看自己的申请
			$is_bool = true;
		}
		if(!$is_bool){
			die('你没有权限查看此申请');
		}
		//
		$WithdrawLog_info['amount']=sprintf('%.2f', $WithdrawLog_info['amount']);
		
		$bills_id=D('WithdrawLog')->getremarks($WithdrawLog_info['remarks']);
		if(count($bills_id)>0){
			$member_bills_ret=M("member_bills")->field('bills_date,income,money,proportion,status')->where(['refid'=>$WithdrawLog_info['uid'],'id'=>['in',$bills_id]])->select();
			foreach($member_bills_ret as $key=>$value){
				$member_bills_ret[$key]['bills_date']=date('Y-m-d',$value['bills_date']);
				$member_bills_ret[$key]['income']=sprintf('%.2f', $value['income']);
				$member_bills_ret[$key]['money']=sprintf('%.2f', $value['money']);
			}
		}
		
		$prefix = C("DB_PREFIX");
        $auth_group_ret = M("auth_group")->field('id,title')->select();
		$auth_group = [];
		foreach($auth_group_ret as $value){
			$auth_group[$value['id']] = $value['title'];
		}
		$this->assign("member_bills_ret", $member_bills_ret);
		$this->assign("auth_group", $auth_group);
		$this->assign("WithdrawLog", $WithdrawLog_info);
		$this->display();
	}
	
	/***
	* 代理打款
	**/
	function play(){
		$status = htmlspecialchars(I("status" , ''));
		$page = I("p", 1, 'intval');
		
		$start_date = htmlspecialchars(I("start_date", ''), ENT_NOQUOTES);
        $end_date = htmlspecialchars(I("end_date", ''), ENT_NOQUOTES);
		$agent_id = I("agent_id", 0, 'intval');

		$status_int = 0;
		if($status == 'paid'){//已打款
			$status_int = 1;
		}
		//获取其所有下级代理
		$uid_ret = M('member')->field('uid,user')->where(['pid'=>session('uid')])->select();
		$uid_arr = [];
		$user_arr = [];
		foreach($uid_ret as $value){
			$uid_arr[] = $value['uid'];
			$user_arr[$value['uid']]=$value['user'];
		}
		if(count($uid_arr)==0){
			$uid_arr = [0];
		}
		
		$pram = [
            'page'      =>  $page,
            'status'   	=>  $status_int,
			'uid'		=>  empty($agent_id)?$uid_arr:$agent_id 
        ];
		
        $page = I("p", 1, 'intval');
		$start_date = htmlspecialchars(I("start_date" , '') , ENT_NOQUOTES);
		$end_date = htmlspecialchars(I("end_date" , '') , ENT_NOQUOTES);
		if(!empty($start_date)){
			//检查日期是否有效
			list($y,$m,$d)=explode('-',$start_date);
			if(checkdate($m,$d,$y)){
				$pram["start_date"] = strtotime($start_date);
			}else{
				$start_date = '';
			}
		}
		if(!empty($end_date)){
			//检查日期是否有效
			list($y,$m,$d)=explode('-',$end_date);
			if(checkdate($m,$d,$y)){
				$pram["end_date"] = strtotime($end_date);
			}else{
				$end_date = '';
			}
		}
		//默认查询当前的数据
		if(empty($start_date) && empty($end_date)){
			$start_date = date('Y-m-d',strtotime("-1 month"));
			$end_date = date('Y-m-d',strtotime("+1 day"));
			$pram["start_date"] = strtotime($start_date);
			$pram["end_date"] = strtotime($end_date);
		}
		$data = D('WithdrawLog')->getList($pram);
		
        $pagebar = new \Think\Page($data['count'], 10);
		foreach($data['list'] as $key=>$value){
			$data['list'][$key]['num'] = $value['basic_success_num']+$value['vip_success_num'];
			$data['list'][$key]['income'] = sprintf('%.2f', $value['money']*($value['proportion']/100));
			$data['list'][$key]['money'] = sprintf('%.2f', $value['money']);
			$data['list'][$key]['user'] = $user_arr[$value['uid']];
		}
		$WLog_data = D("WithdrawLog")->getWLog_count($pram);
		//
		
		$this->assign("WLog_data", $WLog_data);
		$this->assign("data", $data['list']);
        $this->assign("page", $pagebar->show());
		$this->assign("count", $data['count']);
		$this->assign("agent", $user_arr);
		$this->assign("status", $status);
		$this->assign("agent_id", $agent_id);
		$this->assign("start_date", $start_date);
        $this->assign("end_date", $end_date);
        $this->display();
	}
	/***
	* 渠道打款
	**/
	function channels_play(){
		$status = htmlspecialchars(I("status" , ''));
		$page = I("p", 1, 'intval');
		
		$start_date = htmlspecialchars(I("start_date", ''), ENT_NOQUOTES);
        $end_date = htmlspecialchars(I("end_date", ''), ENT_NOQUOTES);
		$agent_id = I("agent_id", 0, 'intval');

		$status_int = 2;
		if($status == 'paid'){//已打款
			$status_int = 1;
		}
		//获取其所有渠道
		$uid_ret = M('member')->field('uid,user')->where(['level'=>3])->select();
		$uid_arr = [];
		$user_arr = [];
		foreach($uid_ret as $value){
			$uid_arr[] = $value['uid'];
			$user_arr[$value['uid']]=$value['user'];
		}
		if(count($uid_arr)==0){
			$uid_arr = [0];
		}
		
		$pram = [
            'page'      =>  $page,
            'status'   	=>  $status_int,
			'uid'		=>  empty($agent_id)?$uid_arr:$agent_id 
        ];
		
		$start_date = htmlspecialchars(I("start_date" , '') , ENT_NOQUOTES);
		$end_date = htmlspecialchars(I("end_date" , '') , ENT_NOQUOTES);
		if(!empty($start_date)){
			//检查日期是否有效
			list($y,$m,$d)=explode('-',$start_date);
			if(checkdate($m,$d,$y)){
				$pram["start_date"] = strtotime($start_date);
			}else{
				$start_date = '';
			}
		}
		if(!empty($end_date)){
			//检查日期是否有效
			list($y,$m,$d)=explode('-',$end_date);
			if(checkdate($m,$d,$y)){
				$pram["end_date"] = strtotime($end_date);
			}else{
				$end_date = '';
			}
		}
		//默认查询当前的数据
		if(empty($start_date) && empty($end_date)){
			$start_date = date('Y-m-d',strtotime("-1 month"));
			$end_date = date('Y-m-d',strtotime("+1 day"));
			$pram["start_date"] = strtotime($start_date);
			$pram["end_date"] = strtotime($end_date);
		}
		$data = D('WithdrawLog')->getList($pram);
		
        $pagebar = new \Think\Page($data['count'], 10);
		foreach($data['list'] as $key=>$value){
			$data['list'][$key]['num'] = $value['basic_success_num']+$value['vip_success_num'];
			$data['list'][$key]['income'] = sprintf('%.2f', $value['money']*($value['proportion']/100));
			$data['list'][$key]['money'] = sprintf('%.2f', $value['money']);
			$data['list'][$key]['user'] = $user_arr[$value['uid']];
		}
		$WLog_data = D("WithdrawLog")->getWLog_count($pram);
		//
		
		$this->assign("WLog_data", $WLog_data);
		$this->assign("data", $data['list']);
        $this->assign("page", $pagebar->show());
		$this->assign("count", $data['count']);
		$this->assign("agent", $user_arr);
		$this->assign("status", $status);
		$this->assign("agent_id", $agent_id);
		$this->assign("start_date", $start_date);
        $this->assign("end_date", $end_date);
        $this->display();
	}
	
	/**
	* 申请打款确认
	**/
	function play_confirm(){
		$id = I("apply", 0, 'intval');
		$play_orderid = htmlspecialchars(I("play_orderid", ''), ENT_NOQUOTES);
		if(empty($id)){
			die(json_encode(['status'=>0,'msg'=>'提现申请编号错误','title'=>'打款确认']));
		}
		if(empty($play_orderid)){
			die(json_encode(['status'=>0,'msg'=>'打款单号为空','title'=>'打款确认']));
		}
		if(strlen($play_orderid)>32){
			die(json_encode(['status'=>0,'msg'=>'打款单号长度不能大于32位','title'=>'打款确认']));
		}
		$WithdrawLog_info = D('WithdrawLog')->selOrderInfo($id);
		if(empty($WithdrawLog_info)){
			die(json_encode(['status'=>0,'msg'=>'你没有权限确认此申请','title'=>'打款确认']));
		}
		
		//获取订单用户的权限
		$member_level = D('Member')->getUserGid($WithdrawLog_info['uid']);
		//var_dump($member_level);
		$is_bool = false;
		if($this->USER['level']==1 && $member_level==3){//超管只能查看所有渠道的申请
			$is_bool = true;
		}elseif($this->USER['level']==3){//渠道只能看自己及其下级代理的申请
			$uid_ret = M('member')->field('uid')->where(['pid'=>session('uid')])->select();
			$uid_arr = [];
			foreach($uid_ret as $value){
				$uid_arr[] = $value['uid'];
			}
			$uid_arr[]=session('uid');
			if(in_array($WithdrawLog_info['uid'],$uid_arr)){
				$is_bool = true;
			}
		}elseif($this->USER['level']==4 && $WithdrawLog_info['uid']==session('uid')){//代理只能查看自己的申请
			$is_bool = true;
		}
		if(!$is_bool){
			die(json_encode(['status'=>0,'msg'=>'你没有权限确认此申请','title'=>'打款确认']));
		}
		$play_orderid_ret = M("withdraw_log")->where(['order_id' => $play_orderid])->find();
		if(!empty($play_orderid_ret)){
			die(json_encode(['status'=>0,'msg'=>'打款单已存在，请重新输入','title'=>'打款确认']));
		}
		if($WithdrawLog_info['status'] == 1){
			die(json_encode(['status'=>0,'msg'=>'申请已确认，不能重复操作','title'=>'打款确认']));
		}
		D("WithdrawLog")->setOrderInfo($WithdrawLog_info['out_biz_no'] , [
			'order_id'  => $play_orderid,
			'pay_time'  => date('Y-m-d H:i:s',time()),
			'status'    => 1,
		]);
		
		$bills_id=D('WithdrawLog')->getremarks($WithdrawLog_info['remarks']);
		if($bills_id && count($bills_id)>0){	
			M("member_bills")->where(['refid'=>$WithdrawLog_info['uid'],'id'=>['in',$bills_id]])->save(['status'=>3]);
		}
		
		die(json_encode(['status'=>1,'msg'=>'打款确认成功','title'=>'打款确认']));
	}
	
	/**
	* 取消申请订单
	**/
	function apply_cancel(){
		$id = I("apply", 0, 'intval');
		if(empty($id)){
			die(json_encode(['status'=>0,'msg'=>'提现申请编号错误','title'=>'申请取消']));
		}
		$WithdrawLog_info = D('WithdrawLog')->selOrderInfo($id);
		if(empty($WithdrawLog_info)){
			die(json_encode(['status'=>0,'msg'=>'你没有权限取消此申请','title'=>'申请取消']));
		}
		//获取订单用户的权限
		$member_level = D('Member')->getUserGid($WithdrawLog_info['uid']);
		//var_dump($member_level);
		$is_bool = false;
		if($this->USER['level']==1 && $member_level==3){//超管只能查看所有渠道的申请
			$is_bool = true;
		}elseif($this->USER['level']==3){//渠道只能看自己及其下级代理的申请
			$uid_ret = M('member')->field('uid')->where(['pid'=>session('uid')])->select();
			$uid_arr = [];
			foreach($uid_ret as $value){
				$uid_arr[] = $value['uid'];
			}
			$uid_arr[]=session('uid');
			if(in_array($WithdrawLog_info['uid'],$uid_arr)){
				$is_bool = true;
			}
		}elseif($this->USER['level']==4 && $WithdrawLog_info['uid']==session('uid')){//代理只能查看自己的申请
			$is_bool = true;
		}
		if(!$is_bool){
			die(json_encode(['status'=>0,'msg'=>'你没有权限取消此申请','title'=>'申请取消']));
		}
		if($WithdrawLog_info['status'] == 1){
			die(json_encode(['status'=>0,'msg'=>'申请已确认，不能取消','title'=>'申请取消']));
		}
		if($WithdrawLog_info['status'] == 2){
			die(json_encode(['status'=>0,'msg'=>'申请已取消，不能重复操作','title'=>'申请取消']));
		}
		
		//开启事务
		M('member')->startTrans();
		//取消申请，回滚申请单对应数据
		$bills_id=D('WithdrawLog')->getremarks($WithdrawLog_info['remarks']);
		if($bills_id && count($bills_id)>0){//将账单还原到未申请
			$member_bills_ret=M("member_bills")->where(['refid'=>$WithdrawLog_info['uid'],'id'=>['in',$bills_id]])->save(['status'=>1]);
		}else{
			$bills_id = [];
		}
		//回滚用户申请金额
		$up_member = M('member')->where(['uid'=>$WithdrawLog_info['uid']])->setInc('money', $WithdrawLog_info['amount']);
		//var_dump($up_member); var_dump($member_bills_ret);var_dump(count($bills_date));
		if ($member_bills_ret == count($bills_id) && $up_member) {//事务完成
			M('member')->commit();
		} else {//回滚
			M('member')->rollback();
			die(json_encode(['status'=>1,'msg'=>'申请取消失败，请重新取消！','title'=>'申请取消']));
		}
		D("WithdrawLog")->setOrderInfo($WithdrawLog_info['out_biz_no'] , [
			'pay_time'  => date('Y-m-d H:i:s',time()),
			'status'    => 2,
		]);
		die(json_encode(['status'=>1,'msg'=>'申请取消成功','title'=>'申请取消']));
	}
	
}
